<template>
  <el-card class="invite-code-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>{{ $t('team.inviteCodes') }}</span>
        <el-button 
          type="primary" 
          size="small"
          :icon="Plus"
          @click="showGenerateDialog = true"
        >
          {{ $t('team.generateCode') }}
        </el-button>
      </div>
    </template>

    <div class="invite-code-list" v-loading="teamStore.inviteCodeLoading">
      <div v-if="activeCodes.length === 0" class="empty-state">
        <el-empty :description="$t('team.noInviteCodes')" :image-size="80">
          <el-button 
            type="primary" 
            @click="showGenerateDialog = true"
          >
            {{ $t('team.generateFirstCode') }}
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="code-list">
        <div 
          v-for="code in activeCodes" 
          :key="code.id"
          class="code-item"
        >
          <div class="code-header">
            <div class="code-value">
              <el-icon><Key /></el-icon>
              <span class="code-text">{{ code.inviteCode }}</span>
              <el-button 
                type="text" 
                size="small"
                :icon="CopyDocument"
                @click="copyCode(code.inviteCode)"
              >
                {{ $t('common.copy') }}
              </el-button>
            </div>
            <el-dropdown trigger="click" @command="(cmd) => handleCodeCommand(cmd, code)">
              <el-button :icon="MoreFilled" circle size="small" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="refresh" :icon="Refresh">
                    {{ $t('team.refreshCode') }}
                  </el-dropdown-item>
                  <el-dropdown-item command="disable" :icon="Close" divided>
                    {{ $t('team.disableCode') }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          
          <div class="code-info">
            <div class="info-item">
              <span class="label">{{ $t('team.inviteRole') }}:</span>
              <el-tag :type="getMemberRoleType(code.inviteRole)" size="small">
                {{ getMemberRoleLabel(code.inviteRole) }}
              </el-tag>
            </div>
            
            <div class="info-item" v-if="code.maxUses">
              <span class="label">{{ $t('team.usageCount') }}:</span>
              <span class="value">{{ code.usedCount }}/{{ code.maxUses }}</span>
            </div>
            
            <div class="info-item" v-if="code.expireTime">
              <span class="label">{{ $t('team.expireTime') }}:</span>
              <span class="value">{{ formatDate(code.expireTime, 'datetime') }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">{{ $t('team.status') }}:</span>
              <el-tag 
                :type="getInviteCodeStatusType(code.status)" 
                size="small"
              >
                {{ getInviteCodeStatusLabel(code.status) }}
              </el-tag>
            </div>
          </div>

          <!-- 使用进度 -->
          <div class="code-progress" v-if="code.maxUses">
            <el-progress 
              :percentage="getUsagePercentage(code)" 
              :stroke-width="4"
              :show-text="false"
              :color="getProgressColor(code)"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 生成邀请码对话框 -->
    <GenerateInviteCodeDialog
      v-model="showGenerateDialog"
      :team-id="teamId"
      @success="handleGenerateSuccess"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { 
  Plus, 
  Key, 
  CopyDocument, 
  MoreFilled, 
  Refresh, 
  Close 
} from '@element-plus/icons-vue'
import { useTeamStore } from '@/stores/teamStore'
import type { TeamInviteCode } from '@/types/team'
import { 
  getMemberRoleLabel, 
  getMemberRoleType,
  getInviteCodeStatusLabel,
  getInviteCodeStatusType
} from '@/types/team'
import { formatDate } from '@/utils/date'
import GenerateInviteCodeDialog from './GenerateInviteCodeDialog.vue'

interface Props {
  teamId: number
}

const props = defineProps<Props>()
const { t } = useI18n()

const teamStore = useTeamStore()
const showGenerateDialog = ref(false)

// 计算属性
const activeCodes = computed(() => teamStore.activeInviteCodes)

// 方法
const refreshCodes = async () => {
  try {
    await teamStore.fetchTeamInviteCodes(props.teamId)
  } catch (error) {
    console.error('刷新邀请码列表失败:', error)
  }
}

const copyCode = async (code: string) => {
  try {
    await navigator.clipboard.writeText(code)
    ElMessage.success(t('team.copySuccess'))
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = code
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success(t('team.copySuccess'))
  }
}

const handleCodeCommand = async (command: string, code: TeamInviteCode) => {
  try {
    switch (command) {
      case 'refresh':
        await teamStore.refreshInviteCode(props.teamId, code.id)
        break
      case 'disable':
        await teamStore.disableInviteCode(props.teamId, code.id)
        break
    }
  } catch (error) {
    console.error('操作邀请码失败:', error)
  }
}

const handleGenerateSuccess = () => {
  showGenerateDialog.value = false
  ElMessage.success(t('team.generateSuccess'))
}

const getUsagePercentage = (code: TeamInviteCode) => {
  if (!code.maxUses) return 0
  return Math.round((code.usedCount / code.maxUses) * 100)
}

const getProgressColor = (code: TeamInviteCode) => {
  const percentage = getUsagePercentage(code)
  if (percentage >= 90) return '#f56c6c'
  if (percentage >= 70) return '#e6a23c'
  return '#67c23a'
}

// 生命周期
onMounted(() => {
  refreshCodes()
})
</script>

<style scoped lang="scss">
.invite-code-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .invite-code-list {
    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 200px;
    }

    .code-list {
      display: flex;
      flex-direction: column;
      gap: 16px;

      .code-item {
        padding: 16px;
        background: var(--el-bg-color-page);
        border-radius: 8px;
        border: 1px solid var(--el-border-color-lighter);

        .code-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .code-value {
            display: flex;
            align-items: center;
            gap: 8px;

            .el-icon {
              color: var(--el-color-primary);
            }

            .code-text {
              font-family: monospace;
              font-size: 16px;
              font-weight: 600;
              color: var(--el-text-color-primary);
              background: var(--el-bg-color);
              padding: 4px 8px;
              border-radius: 4px;
              border: 1px solid var(--el-border-color);
            }
          }
        }

        .code-info {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 8px;
          margin-bottom: 12px;

          .info-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;

            .label {
              color: var(--el-text-color-secondary);
              white-space: nowrap;
            }

            .value {
              color: var(--el-text-color-primary);
              font-weight: 500;
            }
          }
        }

        .code-progress {
          margin-top: 8px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .invite-code-card {
    .card-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }

    .invite-code-list {
      .code-list {
        .code-item {
          .code-header {
            flex-direction: column;
            gap: 12px;
            align-items: flex-start;

            .code-value {
              width: 100%;
              justify-content: space-between;
            }
          }

          .code-info {
            grid-template-columns: 1fr;
          }
        }
      }
    }
  }
}
</style>
